﻿// <copyright file="Label.cs" company="DotNetLib">
//
// .netlib: http://www.codeplex.com/DotNetLib
//
// This code is released under the New BSD License.
// A copy of this license is available at:
// http://www.codeplex.com/DotNetLib/license
//
// </copyright>

namespace DotNetLib.Windows.Forms
{
  using System;
  using WF = System.Windows.Forms;

  public static class ComboBoxExtensions
  {
    public static void AutoSizeDropDownWidth(this WF.ComboBox comboBox)
    {
      if (comboBox == null)
      {
        throw new ArgumentNullException("comboBox");
      }

      if (comboBox.Items.Count == 0)
      {
        comboBox.DropDownWidth = comboBox.Width;
        return;
      }

      using (var graphics = comboBox.CreateGraphics())
      {
        var largestWidth = 0f;
        for (int index = 0; index < comboBox.Items.Count; ++index)
        {
          var itemText = comboBox.GetItemText(comboBox.Items[index]);
          largestWidth = Math.Max(largestWidth, graphics.MeasureString(itemText, comboBox.Font).Width);
        }

        comboBox.DropDownWidth = (int)Math.Ceiling(Math.Max(comboBox.Width, largestWidth + 5));
      }
    }
  }
}
